package cn.zyq.ykb.controller.mgt.system;


import cn.zyq.ykb.beans.sys.SysDept;
import cn.zyq.ykb.service.sys.SysDeptService;
import cn.zyq.ykb.system.annotation.Log;
import cn.zyq.ykb.system.common.BaseController;
import cn.zyq.ykb.system.common.PageParam;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.ry.UserConstants;
import cn.zyq.ykb.system.ry.enums.BusinessType;
import cn.zyq.ykb.system.ry.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/mgt/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @PostMapping("/list")
    public Object list(@RequestBody PageParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SysDept> depts = deptService.list(param, this.getLoginSysAdmin());
        return new PageInfo<>(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public Object excludeChild(@PathVariable(value = "deptId", required = false) Integer deptId) {
        List<SysDept> depts = deptService.list(new PageParam(), this.getLoginSysAdmin());
        depts.removeIf(d -> d.getSysDeptID().equals(deptId) || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return depts;
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public Object getInfo(@PathVariable Integer deptId) {
        deptService.checkDeptDataScope(deptId);
        return deptService.selectDeptById(deptId);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public void add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            throw new BusinessException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        deptService.add(dept, this.getLoginSysAdmin());
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public void edit(@Validated @RequestBody SysDept dept) {
        Integer deptId = dept.getSysDeptID();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            throw new BusinessException("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            throw new BusinessException("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            throw new BusinessException("该部门包含未停用的子部门！");
        }
        deptService.update(dept, this.getLoginSysAdmin());
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public void remove(@PathVariable Integer deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            throw new BusinessException("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            throw new BusinessException("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        this.deptService.deleteDeptById(deptId);
    }
}
